import { Body, Inject, Post } from '@midwayjs/core';
import { CoolController, BaseController, TagTypes, CoolUrlTag, CoolUrlTagData } from '@cool-midway/core';
import { ProductProductEntity } from '../../entity/product';
import { ProductProductService } from '../../service/product';
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { ProductBrandEntity } from '../../entity/brand';

/**
 * 商品信息
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: ProductProductEntity,
  service: ProductProductService,
  pageQueryOp: {
    keyWordLikeFields: ['a.name', 'b.name'],
    fieldEq: ['a.status', 'productCategory'],
    fieldLike: [
      { column: 'a.name', requestParam: 'name' },
      { column: 'b.name', requestParam: 'brandName' },
    ],
    where: async ctx => {
      const { startTime, endTime, priceStart, priceEnd } = ctx.request.body;
      const where = [];
      if (startTime && endTime) {
        where.push([
          'a.purchasingTime >= :startTime AND a.purchasingTime <= :endTime',
          { startTime, endTime },
        ]);
      }
      if (priceStart && priceEnd) {
        where.push([
          'a.price >= :priceStart AND a.price <= :priceEnd',
          { priceStart, priceEnd },
        ]);
      }
      return where;
    },
    join: [
      {
        entity: ProductBrandEntity,
        alias: 'b',
        condition: 'a.brandId = b.id',
        type: 'leftJoin',
      },
      {
        entity: BaseSysUserEntity,
        alias: 'c',
        condition: 'a.purchaserId = c.id',
        type: 'leftJoin',
      },
    ],
    select: ['a.*', 'b.name as brandName', 'c.nickName as purchaserName'],
  },
})


export class AdminProductProductController extends BaseController {
  @Inject()
  productProductService: ProductProductService;

  @Post('/importProducts', { summary: '批量导入商品' })
  async importProducts(@Body() param: { list: any[] }) {
    if (!param.list || !Array.isArray(param.list)) {
      return this.fail('导入数据格式错误');
    }
    const result = await this.productProductService.importProducts(param.list);
    return this.ok(result);
  }
  
  @Post('/getProductTotalMoney', { summary: '获取商品总金额' })
  async getProductTotalMoney(@Body() param: { products: { id: number; count: number }[], couponId?: number }) {
    if (!param.products || param.products.length === 0) 
    return this.ok({
      totalMoney: 0,
      details: [],
      discountMoney: 0,
      currency: 'CNY'
    });
    const result = await this.productProductService.getProductTotalMoney(param.products, param.couponId);
    return this.ok({
      totalMoney: result.money,
      details: result.detail,
      discountMoney: result.totalDiscountAmount,
      discountDetails: result.discountInfo,
      currency: 'CNY' // 示例：可添加更多字段
    })
  }
}